/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.openbravo.pos.sales.restaurant;

import com.openbravo.bean.Customer;
import com.openbravo.bean.PlaceState;
import com.openbravo.data.basic.BasicException;
import com.openbravo.data.gui.MessageInf;
import com.openbravo.pos.base.AppLocal;
import com.openbravo.pos.base.AppView;
import com.openbravo.bean.Place;
import com.openbravo.bean.sales.Ticket;
import com.openbravo.bean.sales.TicketLine;
import com.openbravo.pos.payment.JPaymentSelect;
import com.openbravo.pos.payment.JPaymentSelectReceipt;
import com.openbravo.pos.payment.JPaymentSelectRefund;
import com.openbravo.pos.sales.SaleConfig;
import com.openbravo.pos.sales.TicketsEditor;
import javax.swing.JComponent;
import javax.swing.JOptionPane;

import org.apache.commons.lang.StringUtils;

import java.awt.event.*;
import java.util.Date;

/**
 * 
 * @author Administrator
 */
public class JTicketsBagRestaurantMap extends AbstractJTicketsBagRestaurant {
	protected JTicketsBagRestaurant m_restaurantmap;

	public JTicketsBagRestaurantMap(AppView app, TicketsEditor panelticket) {
		super(app, panelticket, SaleConfig.RESTAURANT_PRINT_PLACESTATE);
		m_restaurantmap = new JTicketsBagRestaurant(app, this);
	}

	@Override
	public JComponent getComponent() {
		return this;
	}

	@Override
	protected ActionListener getPlaceActionListener(Place pl) {
		return new MyActionListener(pl);
	}

	@Override
	public JComponent getBagComponent() {
		return m_restaurantmap;
	}

	private class MyActionListener implements ActionListener {

		private Place m_place;
		private PlaceState currentPlaceState;

		public MyActionListener(Place place) {
			m_place = place;
		}

		private Ticket newTicket() {
			Ticket ticket = new Ticket();
			ticket.setLocation(m_App.getInventoryLocation());
			ticket.setHostName(m_App.getProperties().getHost());
			ticket.setUser(m_App.getAppUserView().getUser().getUserInfo());
			ticket.setM_sGroupName(currentPlaceState.getM_sGroupName());
			ticket.setSaleManager(currentPlaceState.getManager());
			return ticket;
		}

		private void emptyCheck() {
			// tables

			// check if the sharedticket is the same
			Ticket ticket = getTicketInfo(m_place);
			// check
			if (ticket == null && currentPlaceState.hasEnable()) {
				// Empty table and checked

				// table occupied
				ticket = newTicket();
				try {
					dlReceipts.insertSharedTicket(m_place.getId(), ticket);

					currentPlaceState.setBeginTime(new Date());
					currentPlaceState
							.setM_sPlaceState(PlaceState.PLACESTATE_checkin);
					currentPlaceState.setChangeTime(new Date());
					m_dlSales.update(currentPlaceState);

				} catch (BasicException e) {
					new MessageInf(e).show(getComponent()); // Glup. But It was
															// empty.
				}
				setPlaceSelect(m_place, true);
				setActivePlace(m_place, ticket);

			} else if (ticket == null && !currentPlaceState.hasEnable()) {
				// The table is now empty
				new MessageInf(MessageInf.SGN_WARNING,
						AppLocal.getIntString("message.tableempty"))
						.show(getComponent());

				setPlaceSelect(m_place, false);

			} else if (ticket != null && currentPlaceState.hasEnable()) {
				// The table is now full
				new MessageInf(MessageInf.SGN_WARNING,
						AppLocal.getIntString("message.tablefull"))
						.show(getComponent());

				setPlaceSelect(m_place, true);

			} else { // both != null

				if (!clickStateFlag) {
					printPlaceState(m_place, ticket);
				} else {

					boolean isTicketLocked = false;
					try {
						isTicketLocked = dlReceipts
								.isSharedTicketLocked(m_place.getId());
					} catch (BasicException e) {
						new MessageInf(e).show(getComponent());
						return;
					}
					if (isTicketLocked)
						new MessageInf(MessageInf.SGN_WARNING,
								AppLocal.getIntString("message.tablelocked"))
								.show(getComponent());
					else {
						// Full table
						// m_place.setPeople(true); // already true
						ticket.setM_sGroupName(currentPlaceState
								.getM_sGroupName());
						try {
							dlReceipts.lockSharedTicket(m_place.getId(), m_App
									.getAppUserView().getUser().getId());
							setActivePlace(m_place, ticket);
						} catch (BasicException e) {
							new MessageInf(e).show(getComponent());
						}

					}
				}
			}
		}

		private void receiveCheck() {
			// check if the sharedticket is the same
			Ticket ticket = getTicketInfo(m_place);

			if (ticket == null) {
				// receive the customerInfo
				// table occupied
				ticket = newTicket();

				try {
					ticket.setCustomer((Customer) (customerInfo.getId() == null ? null
							: m_dlSales.findByStringId(Customer.class,
									customerInfo.getId())));
				} catch (BasicException e) {
					MessageInf msg = new MessageInf(
							MessageInf.SGN_WARNING,
							AppLocal.getIntString("message.cannotfindcustomer"),
							e);
					msg.show(getComponent());
				}

				try {
					dlReceipts.insertSharedTicket(m_place.getId(), ticket);
				} catch (BasicException e) {
					new MessageInf(e).show(getComponent()); // Glup. But It was
															// empty.
				}

				setPlaceSelect(m_place, true);

				currentPlaceState.setM_sGroupName(null);
				currentPlaceState.setBeginTime(new Date());
				currentPlaceState
						.setM_sPlaceState(PlaceState.PLACESTATE_checkin);
				currentPlaceState.setChangeTime(new Date());
				try {
					m_dlSales.update(currentPlaceState);
				} catch (BasicException e) {
					new MessageInf(e).show(getComponent()); // Glup. But It was
															// empty.
				}
				m_PlaceClipboard = null;
				customerInfo = null;

				setActivePlace(m_place, ticket);
			} else {
				new MessageInf(MessageInf.SGN_WARNING,
						AppLocal.getIntString("message.tablefull"))
						.show(getComponent());

				setPlaceSelect(m_place, true);
				placeButtonMap.get(m_place).setEnabled(false);
			}
		}

		private void moveCheck(Ticket ticketclip) {
			// Moving the receipt to an empty table
			Ticket ticket = getTicketInfo(m_place);
			PlaceState clipboardPlaceState = placeStateMap.get(m_PlaceClipboard
					.getId());

			if (ticket == null) {
				try {
					dlReceipts.insertSharedTicket(m_place.getId(), ticketclip);
					currentPlaceState.setM_sGroupName(clipboardPlaceState
							.getM_sGroupName());
					// dlReceipts.joinGroup(currentPlaceState.getId(),
					// currentPlaceState.getM_sGroupName());
					currentPlaceState.setBeginTime(clipboardPlaceState
							.getBeginTime());
					currentPlaceState.setChangeTime(new Date());
					currentPlaceState
							.setM_sPlaceState(PlaceState.PLACESTATE_checkin);
					try {
						m_dlSales.update(currentPlaceState);
					} catch (BasicException e) {
						new MessageInf(e).show(getComponent()); // Glup. But It
																// was empty.
					}

					setPlaceSelect(m_place, true);

					clearPlace(m_PlaceClipboard);
					// dlReceipts.deleteSharedTicket(m_PlaceClipboard.getId());

					// clipboardPlaceState.setM_sGroupName(null);
					// dlReceipts.joinGroup(clipboardPlaceState.getId(),
					// clipboardPlaceState.getM_sGroupName());
					setPlaceSelect(m_PlaceClipboard, false);
				} catch (BasicException e) {
					new MessageInf(e).show(getComponent()); // Glup. But It was
															// empty.
				}

				m_PlaceClipboard = null;
				customerInfo = null;
				printState();

				// No hace falta preguntar si estaba bloqueado porque ya lo
				// estaba antes
				// activamos el ticket seleccionado
				setActivePlace(m_place, ticketclip);
			} else {// 出现内部逻辑错误，如以被其它先占用。
				// Full table
				new MessageInf(MessageInf.SGN_WARNING,
						AppLocal.getIntString("message.tablefull"))
						.show(getComponent());

				setPlaceSelect(m_PlaceClipboard, true);
				printState();
			}
		}

		private void mageCheck(Ticket ticketclip) {
			PlaceState clipboardPlaceState = placeStateMap.get(m_PlaceClipboard
					.getId());

			// 加入组判断,不同组之间将不能合并
			if (currentPlaceState.getM_sGroupName() != null
					&& !StringUtils.equals(
							clipboardPlaceState.getM_sGroupName(),
							currentPlaceState.getM_sGroupName())) {
				new MessageInf(MessageInf.SGN_WARNING,
						AppLocal.getIntString("message.twotablegroupdeff"))
						.show(getComponent());
				return;
			}

			// Merge the lines with the receipt of the table
			Ticket ticket = getTicketInfo(m_place);

			if (ticket == null) {// 出现内部逻辑错误，如原单据以变其它对应操作。
				// The table is now empty
				new MessageInf(MessageInf.SGN_WARNING,
						AppLocal.getIntString("message.tableempty"))
						.show(getComponent());

				setPlaceSelect(m_place, false);
			} else {

				boolean isTicketLocked = false;
				try {
					isTicketLocked = dlReceipts.isSharedTicketLocked(m_place
							.getId());
				} catch (BasicException e) {
					new MessageInf(e).show(getComponent());
					return;
				}
				if (isTicketLocked) {
					new MessageInf(MessageInf.SGN_WARNING,
							AppLocal.getIntString("message.tablelocked"))
							.show(getComponent());
					return;
				}

				// asks if you want to merge tables
				if (JOptionPane.showConfirmDialog(getComponent(),
						AppLocal.getIntString("message.mergetablequestion"),
						AppLocal.getIntString("message.mergetable"),
						JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
					// 合并开始
					/**
					 * if(m_PlaceClipboard.isGroupPlace()&&!m_place.isGroupPlace
					 * (
					 * )||!m_PlaceClipboard.isGroupPlace()&&m_place.isGroupPlace
					 * ()){ if (JOptionPane.showConfirmDialog(getComponent(),
					 * AppLocal.getIntString("message.mergetablegroupquestion"),
					 * AppLocal.getIntString("message.mergetable"),
					 * JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION){
					 * Place placeclip = m_PlaceClipboard; m_PlaceClipboard =
					 * null; customerInfo = null; printState();
					 * setActivePlace(placeclip, ticketclip); } }else{
					 */
					try {
						/**
						 * ticket.setM_sGroupName(m_PlaceClipboard.
						 * getM_sGroupName());
						 * if(m_PlaceClipboard.isGroupPlace()
						 * &&!m_place.isGroupPlace()){
						 * m_place.setM_sGroupName(m_PlaceClipboard
						 * .getM_sGroupName());
						 * m_PlaceClipboard.setM_sGroupName(null);
						 * m_dlSales.updatePlace(m_PlaceClipboard.getId(),
						 * m_PlaceClipboard);
						 * m_dlSales.updatePlace(m_place.getId(), m_place);
						 * }else if(m_PlaceClipboard.isGroupPlace()&&m_place.
						 * isGroupPlace()){
						 * m_PlaceClipboard.setM_sGroupName(null);
						 * m_dlSales.updatePlace(m_PlaceClipboard.getId(),
						 * m_PlaceClipboard); }
						 * 
						 * ticket.setM_sGroupName(m_place.getM_sGroupName());
						 */
						// dlReceipts.deleteSharedTicket(m_PlaceClipboard.getId());
						clearPlace(m_PlaceClipboard);

						setPlaceSelect(m_PlaceClipboard, false);

						if (ticket.getCustomer() == null) {
							ticket.setCustomer(ticketclip.getCustomer());
						}
						for (TicketLine line : ticketclip.getLines()) {
							ticket.addLine(line);
						}
						dlReceipts.updateSharedTicket(m_place.getId(), ticket,
								m_App.getAppUserView().getUser().getId());
					} catch (BasicException e) {
						new MessageInf(e).show(getComponent()); // Glup. But It
																// was empty.
					}

					m_PlaceClipboard = null;
					customerInfo = null;
					printState();

					setActivePlace(m_place, ticket);
					// }
				} else {// 用户取消，刷新
					// Cancel merge operations
					Place placeclip = m_PlaceClipboard;
					m_PlaceClipboard = null;
					customerInfo = null;
					printState();
					setActivePlace(placeclip, ticketclip);
				}
			}
		}

		@Override
		public void actionPerformed(ActionEvent evt) {
			currentPlaceState = placeStateMap.get(m_place.getId());
			printPlaceState(null, null);
			if (m_PlaceClipboard == null) {// 无原单模式
				if (customerInfo == null) {// 1.普通下单
					emptyCheck();
				} else { // 2.预订下单
					receiveCheck();
				}
			} else {// 原单模式
				// check if the sharedticket is the same
				Ticket ticketclip = getTicketInfo(m_PlaceClipboard);

				if (ticketclip == null) {// 出现内部逻辑错误，如原单据以变其它对应操作。
					new MessageInf(MessageInf.SGN_WARNING,
							AppLocal.getIntString("message.tableempty"))
							.show(getComponent());

					setPlaceSelect(m_PlaceClipboard, false);
					m_PlaceClipboard = null;
					customerInfo = null;
					printState();
				} else {
					// tenemos que copiar el ticket del clipboard
					if (m_PlaceClipboard == m_place) {// 原和目标对象相同，不处理
						// the same button. Canceling.
						Place placeclip = m_PlaceClipboard;
						m_PlaceClipboard = null;
						customerInfo = null;
						printState();
						setActivePlace(placeclip, ticketclip);
					} else if (!currentPlaceState.hasEnable()) {// 目标无单据，进行移位处理
						moveCheck(ticketclip);
					} else {// 目标有单据，进行合并处理
						mageCheck(ticketclip);
					}
				}
			}
		}
	}

	@Override
	public void selectValidTicket() {
	}

	@Override
	public JPaymentSelect getPaymentdialogreceipt() {
		return JPaymentSelectReceipt.getDialog(this);
	}

	@Override
	public JPaymentSelect getPaymentdialogrefund() {
		return JPaymentSelectRefund.getDialog(this);
	}

	@Override
	public void showNextTicket() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void showPrevTicket() {
		// TODO Auto-generated method stub
		
	}

}
